package service

import (
	"context"
	"fmt"
	"time"

	"gitee.com/liumou_site/go-network-monitoring/types"
	"gitee.com/liumou_site/go-network-monitoring/utils"
	"gitee.com/liumou_site/logger"
	"github.com/shirou/gopsutil/v3/net"
)

// NetworkService 网络监控服务
type NetworkService struct {
	responseBuilder *NetworkResponseBuilder
}

// NewNetworkService 创建网络监控服务实例
func NewNetworkService() *NetworkService {
	return &NetworkService{
		responseBuilder: NewNetworkResponseBuilder(),
	}
}

// GetNetworkStats 获取所有网络接口的统计信息
func (ns *NetworkService) GetNetworkStats() (map[string]*types.NetData, error) {
	result := make(map[string]*types.NetData)
	ioCounters, err := net.IOCounters(true)
	if err != nil {
		return result, fmt.Errorf("failed to get network io counters: %v", err)
	}

	for _, counter := range ioCounters {
		// 跳过回环接口
		if counter.Name == "lo" || counter.Name == "Loopback" {
			continue
		}

		data := &types.NetData{
			Received:      counter.BytesRecv,
			Sent:          counter.BytesSent,
			TotalUpload:   counter.BytesSent,
			TotalDownload: counter.BytesRecv,
			TotalDropped:  counter.Dropin + counter.Dropout,
			Packets:       counter.PacketsRecv + counter.PacketsSent,
			IsVirtual:     utils.IsVirtualInterface(counter.Name),
		}

		// 只包含有流量的接口
		if data.Received > 0 || data.Sent > 0 {
			result[counter.Name] = data
		}
	}

	if len(result) == 0 {
		return result, fmt.Errorf("no active network interfaces found")
	}

	return result, nil
}

// CalculateSpeed 计算所有网络接口的速度
func (ns *NetworkService) CalculateSpeed(ctx context.Context, interval time.Duration) (map[string]*types.SpeedData, map[string]*types.NetData, error) {
	speedData := make(map[string]*types.SpeedData)
	netData := make(map[string]*types.NetData)

	logger.Debug("calculateSpeed called for all interfaces, interval:", interval)

	// 获取初始状态
	res1, err := ns.GetNetworkStats()
	if err != nil {
		logger.Error("Error getting initial network stats:", err)
		return nil, nil, fmt.Errorf("error getting initial network stats: %v", err)
	}

	select {
	case <-time.After(interval):
	case <-ctx.Done():
		logger.Error("Context canceled while waiting for interval")
		return nil, nil, ctx.Err()
	}

	// 获取最终状态
	res2, err := ns.GetNetworkStats()
	if err != nil {
		logger.Error("Error getting final network stats:", err)
		return nil, nil, fmt.Errorf("error getting final network stats: %v", err)
	}

	// 计算每个接口的速度
	for name := range res1 {
		if res2[name] == nil || res1[name] == nil {
			continue
		}

		// 跳过没有变化的接口
		if res1[name].Received == res2[name].Received && res1[name].Sent == res2[name].Sent {
			continue
		}

		// 检查数据溢出
		if res2[name].Received < res1[name].Received || res2[name].Sent < res1[name].Sent {
			logger.Error("Overflow detected in network stats for interface", name)
			continue
		}

		receivedDiff := res2[name].Received - res1[name].Received
		sentDiff := res2[name].Sent - res1[name].Sent

		speedData[name] = &types.SpeedData{
			DownloadSpeed: float64(receivedDiff),
			UploadSpeed:   float64(sentDiff),
		}

		netData[name] = &types.NetData{
			Received:      uint64(float64(receivedDiff) / interval.Seconds()),
			Sent:          uint64(float64(sentDiff) / interval.Seconds()),
			TotalDownload: res2[name].TotalDownload,
			TotalUpload:   res2[name].TotalUpload,
			TotalDropped:  res2[name].TotalDropped,
			Packets:       res2[name].Packets,
			IsVirtual:     res2[name].IsVirtual,
		}
	}

	if len(speedData) == 0 {
		return speedData, netData, fmt.Errorf("no active network interfaces with traffic")
	}

	return speedData, netData, nil
}

// GetInterfaceList 获取所有网卡的基本信息列表
func (ns *NetworkService) GetInterfaceList() ([]*types.InterfaceInfo, error) {
	interfaces := make([]*types.InterfaceInfo, 0)

	// 获取所有网络接口
	ioCounters, err := net.IOCounters(true)
	if err != nil {
		return interfaces, fmt.Errorf("failed to get network interfaces: %v", err)
	}

	for _, counter := range ioCounters {
		// 跳过回环接口
		if utils.IsLoopbackInterface(counter.Name) {
			continue
		}

		isVirtual := utils.IsVirtualInterface(counter.Name)
		interfaceType := "physical"
		if isVirtual {
			interfaceType = "virtual"
		}

		status := "inactive"
		if counter.BytesRecv > 0 || counter.BytesSent > 0 {
			status = "active"
		}

		info := &types.InterfaceInfo{
			ID:        utils.GenerateInterfaceID(counter.Name),
			Name:      counter.Name,
			Type:      interfaceType,
			IsVirtual: isVirtual,
			Status:    status,
		}

		interfaces = append(interfaces, info)
	}

	return interfaces, nil
}

// BuildNetworkAPIResponse 构建网络API响应
func (ns *NetworkService) BuildNetworkAPIResponse(allStats map[string]*types.NetData, speedStats map[string]*types.SpeedData) types.NetworkAPIResponse {
	return ns.responseBuilder.BuildNetworkAPIResponse(allStats, speedStats)
}

// BuildSpeedAPIResponse 构建SSE API响应
func (ns *NetworkService) BuildSpeedAPIResponse(allStats map[string]*types.NetData, speedStats map[string]*types.SpeedData) types.SpeedAPIResponse {
	return ns.responseBuilder.BuildSpeedAPIResponse(allStats, speedStats)
}

// BuildInterfaceListResponse 构建网卡列表响应
func (ns *NetworkService) BuildInterfaceListResponse(interfaces []*types.InterfaceInfo) types.InterfaceListResponse {
	return ns.responseBuilder.BuildInterfaceListResponse(interfaces)
}
